// 登录鉴权
import { Navigate, useLocation } from 'react-router'
import { useEffect } from 'react'
import checkLogin from '@/utils/checkLogin.ts'
import { get } from '@/utils/request'
import { useAppDispatch, useAppSelector } from '@/hooks/useStore'
import { setUserInfo, userInfoType } from '@/store/userReducer'
const AuthProvider = (props: { children: React.ReactNode }) => {
  const { children } = props
  if (!checkLogin()) {
    // 如果没有授权，则跳转到登录页面
    return <Navigate to="/login" />
  }
  const { pathname } = useLocation()
  const dispath = useAppDispatch()
  const userInfo = useAppSelector((state) => state.user as userInfoType)
  const fetchUserInfo = () => {
    get('/api/v1/user/profile').then((res) => {
      dispath(setUserInfo(res as unknown as userInfoType))
    })
  }
  useEffect(() => {
    !userInfo?.id && fetchUserInfo()
  }, [])

  return <>{pathname === '/' ? <Navigate to="/dashboard/workplace" /> : <>{children}</>}</>
}

export default AuthProvider
